<div style="padding:20px;" id="container_h_#handler.handler_id">
<? $defaultBespinOptions = ', "settings": {"fontsize": 10, "tabstop": 4, "theme": "white", "autoindent": true}, "stealFocus": true'; ?>
<form id="hformh<?=(int)$arr_param["handler"]["handler_id"]?>" method="post" action="?" onsubmit="try{$('container_h_#handler.handler_id').save();}catch(e){};return false;">
	<div style="float:left;width:49%;margin-right:1%;">
		<label for="name">Name of event handler</label><br/>
		<input id="h_event_#handler.handler_id" type="text" name="handler[event]" value="#handler.event" /><br/><br/>
		<input id="h_eventh_#handler.handler_id" type="hidden" value="#handler.event" />
	</div>
	<div style="float:left;width:50%;">
		<div style="float:left;width: 30%;">
			<input type="checkbox" name="handler[flag_ajax]" value="1" id="ajax_#handler.handler_id"<?=($arr_param["handler"]["flag_ajax"] == "1" ? " checked='checked'":"")?> />
			<label for="ajax_#handler.handler_id">is AJAX event <a title="normally pages are wrapped in a base template. If you don't want that (mostly because the event is called via AJAX), tick this checkbox." class="builder-help"> ? </a></label><br/>
			<input type="checkbox" name="handler[flag_cacheable]" value="1" id="cache_#handler.handler_id"<?=($arr_param["handler"]["flag_cacheable"] == "1" ? " checked='checked'":"")?> />
        	<label for="cache_#handler.handler_id">output is cacheable <a title="if this is ticked, the result will be cached for all same GET requests to this event (until you remove it)." class="builder-help"> ? </a></label>
    	</div>
        <div style="float:left;width: 70%;">
        	<input type="checkbox" name="schedule" value="1" onclick="if(this.checked){$('container_h_#handler.handler_id').schedule(this);}else{$('hschedule#handler.handler_id').value=$('jobdetails_#handler.handler_id').innerHTML='';}" id="job_#handler.handler_id"<?=(strlen($arr_param['handler']['hook']) <= 0 && strlen($arr_param['handler']['schedule']) > 0 ? " checked='checked'" : "")?> />
        	<label for="job_#handler.handler_id">is a job <a title="a job will be called periodically - independent of page requests by users." class="builder-help"> ? </a><span id="jobdetails_#handler.handler_id"></span></label>
        	<input type="hidden" name="handler[schedule]" value='#handler.schedule' id="hschedule#handler.handler_id" />
        	<br/>
        	<input type="checkbox" name="hook" value="1" id="hook_#handler.handler_id"<?=(strlen($arr_param["handler"]["hook"]) > 0 ? " checked='checked'":"")?> onclick="if(!this.checked)$('hook_name#handler.handler_id').value='';$('hook_name#handler.handler_id').toggle();" />
        	<label for="hook_#handler.handler_id">is a hook <a title="in order to be called as soon as a certain hook sink (defined via <c:hook> or HookCore::notify) is executed, tick this." class="builder-help"> ? </a></label>
        	<input type="text" name="handler[hook]" value="#handler.hook" id="hook_name#handler.handler_id" style="<?=(strlen($arr_param["handler"]["hook"]) > 0 ? "" : "display:none;")?>" />
        </div>
		<div style="clear:both;"></div>
	</div>
	<div style="clear:both;"></div>
	<div style="float:left;margin-right:1%;width:49%;position:relative;">
		<div style="position:absolute;right:0px;">
			<a href="#" onclick="this.next().show();this.hide();this.parentNode.parentNode.next().hide();this.parentNode.parentNode.style.width='100%';return false;" title="maximize code view"><img src="templates/builder/images/icon_maximize.gif" border="0" alt="maximize code view" /></a>
			<a href="#" style="display:none;" onclick="this.previous().show();this.hide();this.parentNode.parentNode.next().show();this.parentNode.parentNode.style.width='49%';return false;" title="minimize code view"><img src="templates/builder/images/icon_minimize.gif" border="0" alt="minimize code view" /></a>
		</div>
		<label for="code<?=(int)$arr_param["handler"]["handler_id"]?>">Handler Code <a title="In this area you can put your actual business logic as PHP code. You can call the String out(Array) function to call the output code. Return it to send it to the browser." class="builder-help"> ? </a>:</label><br/>
		<input type="hidden" id="hCodeh<?=(int)$arr_param["handler"]["handler_id"]?>" name="handler[code]" value="" />
		<div rel="call:hcodehSet(#handler.handler_id)" id="hcodehcontainer#handler.handler_id" class="tab-list">
		<? if (is_array($arr_param['codes'])) foreach ($arr_param['codes'] as $code) { ?>
			<div class="x-tab" style="height:100%;" title="<?=$code['title']?>">
				<!--[noeval]-->
				<div style="border:0px solid #ccc;height:100%;" title="<?=$code['title']?>" class="hcodeh" rel="builder:editHandler&refresh=code&handler_id=<?=(int)$arr_param["handler"]["handler_id"]?>" id="codeh<?=(int)$arr_param['handler']['handler_id']?><?=$code['id']?>" data-bespinoptions='{"syntax": "php"<?=$defaultBespinOptions?>}'><?=htmlspecialchars($code["content"])?></div>
				<!--[/noeval]-->
			</div>
		<? } ?>
		</div>
	</div>
	<div style="float:left;width:50%;position:relative;">
		<div style="position:absolute;right:0px;">
			<a href="#" onclick="this.next().show();this.hide();this.parentNode.parentNode.previous().hide();this.parentNode.parentNode.style.width='100%';return false;" title="maximize code view"><img src="templates/builder/images/icon_maximize.gif" border="0" alt="maximize code view" /></a>
			<a href="#" style="display:none;" onclick="this.previous().show();this.hide();this.parentNode.parentNode.previous().show();this.parentNode.parentNode.style.width='50%';return false;" title="minimize code view"><img src="templates/builder/images/icon_minimize.gif" border="0" alt="minimize code view" /></a>
		</div>
		<label for="html_code<?=(int)$arr_param["handler"]["handler_id"]?>">Output Code <a title="In this area you can put the HTML code to be presented to the user" class="builder-help"> ? </a>:</label><br/>
		<input type="hidden" id="hHtmlCodeh<?=(int)$arr_param["handler"]["handler_id"]?>" name="handler[html_code]" value="" />
		<div rel="call:hhtmlcodehSet(#handler.handler_id)" id="hhtmlcodehcontainer#handler.handler_id" class="tab-list">
		<? if (is_array($arr_param['html_codes'])) foreach ($arr_param['html_codes'] as $code) { ?>
			<div class="x-tab" style="height:100%;" title="<?=$code['title']?>">
				<!--[noeval]-->
				<div title="<?=$code['title']?>" style="border:0px solid #ccc;height:100%;" class="hhtmlcodeh" rel="builder:editHandler&refresh=html_code&handler_id=<?=(int)$arr_param["handler"]["handler_id"]?>" id="html_codeh<?=(int)$arr_param['handler']['handler_id'].$code['id']?>" data-bespinoptions='{"syntax": "php", "html": true<?=$defaultBespinOptions?>}'><?=htmlspecialchars($code["content"])?></div>
    			<!--[/noeval]-->		
			</div>
		<? } ?>
		</div>
	</div>
	<div style="display: none;" id="schedule_#handler.handler_id">
		<div class="scheduler">
			<div class="form-entry date">
				<div class="label">
					<label for="from">Active:</label>
				</div>
				<div class="value">
					<input type="date" value="<?=date('Y-m-d')?>" name="active" />
				</div>
			</div>
			<div class="form-entry time">
				<div class="label">
					<label for="from">Run Time:</label>
				</div>
				<div class="value">
					<input type="time" value="<?=date('H:i')?>" name="runtime" />
				</div>
			</div>
			<div class="form-entry repeat">
				<div class="label">
					<label for="from">Every:</label>
				</div>
				<div class="value">
					<input type="text" name="repeat" value="1" />
					<select name="type" size="1">
						<option value="mins">Minutes</option>
						<option value="hours">Hours</option>
						<option value="days" selected="selected">Days</option>
						<option value="months">Months</option>						
					</select>
				</div>
			</div>
			<div class="form-entry days">
				<div class="label">
					<label for="from">On these days:</label>
				</div>
				<div class="value radiogroup">
					<div class="radio">
						<input type="checkbox" name="weekday[mon]" value="1" checked="checked" id="mon_#handler.handler_id" /> 
						<label for="mon_#handler.handler_id">Monday</label>
					</div>
					<div class="radio">
						<input type="checkbox" name="weekday[tue]" value="2" checked="checked" id="tue_#handler.handler_id" /> 
						<label for="tue_#handler.handler_id">Tuesday</label>
					</div>
					<div class="radio">
						<input type="checkbox" name="weekday[wed]" value="3" checked="checked" id="wed_#handler.handler_id" /> 
						<label for="wed_#handler.handler_id">Wednesday</label>
					</div>
					<div class="radio">
						<input type="checkbox" name="weekday[thu]" value="4" checked="checked" id="thu_#handler.handler_id" /> 
						<label for="thu_#handler.handler_id">Thursday</label>
					</div>
					<div class="radio">
						<input type="checkbox" name="weekday[fri]" value="5" checked="checked" id="fri_#handler.handler_id" /> 
						<label for="fri_#handler.handler_id">Friday</label>
					</div>
					<div class="radio">
						<input type="checkbox" name="weekday[sat]" value="6" checked="checked" id="sat_#handler.handler_id" /> 
						<label for="sat_#handler.handler_id">Saturday</label>
					</div>
					<div class="radio">
						<input type="checkbox" name="weekday[sun]" value="0" checked="checked" id="sun_#handler.handler_id" /> 
						<label for="sun_#handler.handler_id">Sunday</label>
					</div>
				</div>
			</div>
		</div>
	</div>
	<div id="endpoint_#handler.handler_id" style="display:none;"><div title="[name]" class="hcodeh" rel="builder:editHandler&refresh=code&handler_id=<?=(int)$arr_param["handler"]["handler_id"]?>" id="codeh<?=(int)$arr_param['handler']['handler_id']?>[name]" data-bespinoptions='{"syntax": "php"<?=$defaultBespinOptions?>}' onload="$('container_h_#handler.handler_id').addKeywords"><?=htmlentities(file_get_contents("templates/builder/php/handler_form_empty.php"))?></div></div>	
	<div id="template_#handler.handler_id" style="display:none;"><div title="[name]" class="hhtmlcodeh" rel="builder:editHandler&refresh=code&handler_id=<?=(int)$arr_param["handler"]["handler_id"]?>" id="html_codeh<?=(int)$arr_param['handler']['handler_id']?>[name]" data-bespinoptions='{"syntax": "php", "html": true<?=$defaultBespinOptions?>}'><?=htmlentities(file_get_contents("templates/builder/php/output_empty.php"))?></div></div>	
	<div style="clear:both;"></div>
	<br/>
	<script type="text/javascript">
	//<![CDATA[
		window.keywords = [	"list", "foreach", "array", "in", "include", "die", "echo", "empty", "exit", "eval", "include_once", "isset",
							"require", "require_once", "return", "print", "unset", "case", "class", "abstract", "and", "as", "break",
							"catch", "clone", "const", "continue", "declare", "default", "do", "else", "elseif", "enddeclare", "endfor",
							"endforeach", "endif", "endswitch", "endwhile", "extends", "final", "for", "foreach", "function", "global",
							"goto", "if", "implements", "interface", "instanceof", "namespace", "new", "or", "private", "protected",
							"public", "static", "switch", "throw", "try", "use", "var", "while", "xor"
		];
		setTimeout(function() {
			window["scheduler#handler.handler_id"] = $("schedule_#handler.handler_id").cloneNode(true);
			$("schedule_#handler.handler_id").remove();
			var data = eval("("+($("hschedule#handler.handler_id").value || "{}")+")");
			if (data["time"]) {
				var dateInfo = "every";
				for (var all in data) {
					if (all != "week") {
						if (data[all][0] == "*") {
							dateInfo += " "+data[all].split("/")[1]+" "+all+"s";
						}
					}
				}
				dateInfo += " from "+data["date"];
				dateInfo += " at "+data["time"];
				$("jobdetails_#handler.handler_id").innerHTML = " ("+dateInfo+" <a href='javascript:$(\"container_h_#handler.handler_id\").schedule(null);'>change</a>)";				
			}

			window.hcodehSet = function(handlerId, code) {
		        var lastPos = 0;
		        var codes = [];
		        codes.push({title: "Default", id: "hcode_"+handlerId});
		        var re = /\/\*\[BEGIN POST-([^\]]+)\]\*\//gi;
				while(matches = re.exec(code)) {
			        if (matches[1]) {
			        	var match = matches[1];
			        	var cd = {title: matches[0], id: "code_"+match+handlerId}; 
			        	var start = code.indexOf("/"+"*[ACTUAL]*"+"/", matches.index) + ("/"+"*[ACTUAL]*"+"/").length + 1;
			        	var end = code.indexOf("/"+"*[END ACTUAL]*"+"/", start);
			        	cd["content"] = code.substr(start, end - start);
			        	lastPos = code.indexOf("/"+"*[END POST-"+match+"]*"+"/\n", matches.index) + ("/"+"*[END POST-"+match+"]*"+"/\n").length;
			        	codes.push(cd);
			        }
		        }
		        codes[0]["content"] = code.substr(lastPos);

		        $A(codes).each(function(item) {
		        	Builder.setCode("codeh"+handlerId+item.id, item.content);
		        });
			};
			window.hhtmlcodehSet = function(handlerId, code) {
		        var lastPos = 0;
		        var codes = [];
		        var re = /<part-([^>]+)>/gi;
		        codes.push({title: "Default", id: "html_"+handlerId});
		        while (matches = re.exec(code)) {
			        if (matches[1]) {
			        	var match = matches[1];
			        	var cd = {title: matches[0], id: "html_"+match+handlerId}; 
			        	var start = matches.index + ("<part-"+match+">\n").length;
			        	var end = code.indexOf("</part-"+match+">\n", start);
			        	cd["content"] = code.substr(start, end - start);
			        	lastPos = code.indexOf("</part-"+match+">\n", start) + ("</part-"+match+">\n").length;
			        	codes.push(cd);
			        }
		        }
		        codes[0]["content"] = code.substr(lastPos);

		        $A(codes).each(function(item) {
		        	Builder.setCode("html_codeh"+handlerId+item.id, item.content);
		        });		        
			};

			$("container_h_#handler.handler_id").schedule = function(el) {
				$("container_h_#handler.handler_id").scheduleWindow = new Ext.Window({
					title: "Schedule Job",
					closable: true,
					width: 400,
					shadow: true,
					height: "auto",
					modal: false, 
					html: window["scheduler#handler.handler_id"].innerHTML,
					bbar: [{
						xtype: "button",
						text: "Ok",
						handler: function() {
							var date = $$(".scheduler .date input")[0].value;
							var time = $$(".scheduler .time input")[0].value;
							var repeat = $$(".scheduler .repeat input")[0].value;
							var repInt = $$(".scheduler .repeat select")[0].value;
							var days = $$(".scheduler .days input");
							var dlist = [];
							days.each(function(d){
								if (d.checked) {
									dlist.push(d.value);
								}
							});
							
							var crontab = {
								min: (repInt == 'mins' ? "*/"+repeat : time.split(":")[1]),
								hour: (repInt == 'hours' ? "*/"+repeat : time.split(":")[0]),
								day: (repInt == 'days' ? "*/"+repeat : date.split("-")[2]),
								month: (repInt == 'months' ? "*/"+repeat : date.split("-")[1]),
								week: dlist.join(","),
								time: time,
								date: date								
							};
							$("hschedule#handler.handler_id").value = JSON.stringify(crontab);
							
							dateInfo = "every "+repeat+" "+repInt+" from "+date+" at "+time;
							$("jobdetails_#handler.handler_id").innerHTML = " ("+dateInfo+" <a href='javascript:$(\"container_h_#handler.handler_id\").schedule(null);'>change</a>)";
							
							$("container_h_#handler.handler_id").scheduleWindow.close();
						}
					}, {
						xtype: "button",
						text: "Cancel",
						handler: function() {
							$("container_h_#handler.handler_id").scheduleWindow.close();
						}
					}]
				});
				$("container_h_#handler.handler_id").scheduleWindow.show();
				var data = eval("("+($("hschedule#handler.handler_id").value || "{}")+")");
				for (var all in data) {
					if (all != "week") {
						if (data[all][0] == "*") {
							$$(".scheduler .repeat input")[0].value = data[all].split("/")[1];
							$$(".scheduler .repeat select option").each(function(item) {
								if (item.value == all+"s") {
									item.selected = true;
									throw $break;
								}
							}); 
						}
					} else {
						$$(".scheduler .days input").each(function(input) {
							if ((data[all]+",").indexOf(input.value) >= 0) {
								input.checked = true;
							} else {
								input.checked = false;
							}
						});
					}
				}
				$$(".scheduler .time input")[0].value = data["time"] || "<?=date('H:i')?>";
				$$(".scheduler .date input")[0].value = data["date"] || "<?=date('Y-m-d')?>";
			};
			
      $("container_h_#handler.handler_id").save = function(onlyMerge) {
    	  if (this.saving) return;
    	  this.saving = true;
    	  if (onlyMerge !== true) {
    	  	document.title = "Saving handler "+$("h_event_#handler.handler_id").getValue()+"...";
    	  }
    	  $("h_event_#handler.handler_id").value = $("h_event_#handler.handler_id").getValue().replace(/[^a-zA-Z0-9_]/gi, ''); 
          if (window.keywords.indexOf($("h_event_#handler.handler_id").getValue()) >= 0) {
            $("h_event_#handler.handler_id").value = "_"+$("h_event_#handler.handler_id").getValue();
          }
    	  if (onlyMerge !== true) {
	          if ($("h_event_#handler.handler_id").getValue().length <= 0 || $("h_event_#handler.handler_id").getValue().match(/^[^a-zA-Z_]/gi)) {
	        	  if ($("h_event_#handler.handler_id").getValue().match(/^[^a-zA-Z_]/gi)) {
	        		Ext.Msg.alert("Problem", "The handler's name is invalid. Please check.");  
	        	  } else {
	        	  	Ext.Msg.alert("Problem", "Please specify the handler's name.");
	        	  }
	        	  document.title = "Prails Home";
	        	  this.saving = false;
	        	  return;
	          }
    	  }
          
       	  //$('hHtmlCodeh<?=(int)$arr_param["handler"]["handler_id"]?>').value=Builder.getCode("html_codeh<?=(int)$arr_param['handler']['handler_id']?>");
          $('hHtmlCodeh<?=(int)$arr_param["handler"]["handler_id"]?>').value = "";
          var titles = {};
          $('container_h_<?=$arr_param['handler']['handler_id']?>').select(".tab-list .hhtmlcodeh").each(function(item) {
        	  var it = Builder.getCode(item);
        	  var t = item.title;
        	  if (titles[t]) return;
        	  titles[t] = true;
        	  if (t != "Default") {
	        	  it = "<part-"+t+">\n"+it+"</part-"+t+">\n";
        	  }
              $('hHtmlCodeh<?=(int)$arr_param["handler"]["handler_id"]?>').value = it + $('hHtmlCodeh<?=(int)$arr_param["handler"]["handler_id"]?>').value;
          });
       	  
          // accumulate all code segments into one
          var titles = {};
          $('hCodeh<?=(int)$arr_param["handler"]["handler_id"]?>').value = "";
          $('container_h_<?=$arr_param['handler']['handler_id']?>').select(".tab-list .hcodeh").each(function(item) {
        	  var it = Builder.getCode(item);
        	  var t = item.title;
        	  if (titles[t]) return;
        	  titles[t] = true;
        	  if (t != "Default") {
	        	  it = "/*[BEGIN POST-"+t+"]*/\nif (isset($_POST[\""+t+"\"])) { /*[ACTUAL]*/\n"+it+"/*[END ACTUAL]*/\nsession_write_close();\ndie();}\n/*[END POST-"+t+"]*/\n";
        	  }
              $('hCodeh<?=(int)$arr_param["handler"]["handler_id"]?>').value = it + $('hCodeh<?=(int)$arr_param["handler"]["handler_id"]?>').value;
          });
          var me = this;
    	  if (onlyMerge === true) {
        	  this.saving = false;
    		  return;
    	  }
          invoke(null, 'builder:editHandler&check=1&module_id=<?=if_set($arr_param['handler']['fk_module_id'], $_SESSION["module_id"])?>&handler_id=<?=(int)$arr_param['handler']['handler_id']?>', $('hformh<?=(int)$arr_param["handler"]["handler_id"]?>').serialize(), true, function(req) {
        	  me.saving = false;
        	  Ext.ux.util.msg("Saving completed.", "Your changes have been saved successfully.");
        	  document.title = "Prails Home";

        	  try {
			  	$("html_codeh<?=(int)$arr_param['handler']['handler_id']?>").crc.content = Builder.getCode("html_codeh<?=(int)$arr_param['handler']['handler_id']?>");
    	   	    $("html_codeh<?=(int)$arr_param['handler']['handler_id']?>").dirty = false;
        	  } catch(e){console.log(e, e.message);};
        	  $('container_h_<?=$arr_param['handler']['handler_id']?>').select(".tab-list .hcodeh").each(function(item) {
        		  try {
        			  item.crc.content = Builder.getCode(item);
	        		  item.dirty = false;
        		  } catch(e) { console.log(e, e.message); };
        	  });
        	  
            if (<?=(int)$arr_param["handler"]["handler_id"]?> == 0) {
              var name = $("h_event_#handler.handler_id").getValue();
              var id = req.responseText.split(/\s/g)[0];
              var mid = <?=(int)$_SESSION["module_id"]?>;
              var module = Builder.root.findChild("id", mid);
              Builder.closeTab("h_0");
              var n = new Ext.tree.TreeNode({
                text: name,
                leaf: true,
                id: "h_"+id,
                allowChildren: false
              });
              module.handlers.push(n);
              Builder.editHandler(n);
              Builder.resetTree(Builder.handlerRoot, module.handlers);
            }
          });
          return false;     
      };
            
      (function() {
 	     var initBespin = function(list) {
 	     	var item = list.pop();
 	      	if (!item || !$(item)) {
      			setTimeout(function() {
         	    	$("container_h_#handler.handler_id").save(true);
      			}, 100);
 	      		return;
 	      	}
 		    Builder.applyBespin(item, function(fr) {
 			    	$("container_h_#handler.handler_id").addKeywords = function(txt) {
 		        		txt.addKeywords(null, function(txt) {
 		        			var res = [];
 		        			var matches = txt.getCode().match(/\$[a-zA-Z_][a-zA-Z_0-9]*\b/gi);
 		        			if (matches) {
 			        			for (var a = 0; a < matches.length; a++) {
 			        				if ((",$arr_param,$data,$SERVER,$SECURE_SERVER,$currentLang,$_GET,$_POST,$_REQUEST,$_COOKIE,$_SERVER,"+res.join(",")+",").indexOf(matches[a]) < 0) {
 			        					res.push(matches[a]);
 			        				}
 			        			}
 		        			}
 		        			return res;
 		        		});
 			          	var arr = [];
 			          	$A(Builder.root.findChild("id", <?=(int)$_SESSION["module_id"]?>).datas).each(function(item) {
 			          		arr.push(item.text);
 			          	});
 			          	txt.addKeywords("\\$data->", arr);
 			          	txt.addKeywords("Generator::", ["getInstance()"]);
 			          	txt.addKeywords("Generator::getInstance\\(\\)->", ["getTitle()", "setTitle(\"New Title\")", "getDescription()", "setDescription($description)", "setIsAjax(true)", "setKeywords($keywords)", "addHeader(\"<meta name='robots' content='index, follow' />\")", "getLanguage()"]);
 			          	txt.addKeywords("Generator::getInstance\\(\\)->getLanguage\\(\\)->", ["getText($identifier)", "selectTextByIdentifier($itentifier)", "listAllTextsFromRoot($rootIdentifier)", "findTextByContent($searchString)", "getAllTextsByIdentifier($identifier)"]);
 			          	txt.addKeywords("\\$currentLang->", ["getText($identifier)", "selectTextByIdentifier($itentifier)", "listAllTextsFromRoot($rootIdentifier)", "findTextByContent($searchString)", "getAllTextsByIdentifier($identifier)"]);
 			          	txt.addKeywords(null, ["$_SERVER", "$_COOKIE", "$_REQUEST", "$_GET", "$_POST", "$data", "$arr_param", "$SERVER", "$SECURE_SERVER", "$currentLang", "out($arr_param)", "invoke($event, $arr_param)", "checkFields($arr_toCheck, $arr_keys)", "Generator", "scaleEmbed($embed, $width, $height)", "isEmbed($embed)", "isExternalURL($string)", "if_set($a, $b)", "set_var($a, $b)", "getUserLanguage($arr_allowedLanguages, $defaultLanguage)", "wordCut($text, 200, \"...\")", "removeDir($path, true)", "hyperlink($text)", "timeDiff($time)", "toUTF8($string)", "jumpTo($url)", "createThumbnail($src, $dest, 64, 64)", "getThumbnailFromEmbed($embed)", "sendMail($to, $subject, $content, $fromName, $fromAddress)", "doGet($url)", "doPost($url, $postData)", "array_merge_recursive_distinct($arr1, $arr2)", "one_of($a, $b, ...)", "receiveFile($fileName, $targetPath)"]);
 			          	txt.addKeywords(null, <?=json_encode($arr_param['configurations'])?>);
 		        	};
 		        	$("container_h_#handler.handler_id").addKeywords(fr.txt);
 		          	
 					initBespin(list);
 			    }, Object.extend(Builder.prailsNamespace, {
 					id: "container_h_#handler.handler_id",
 					save: function() {
 						parent.$("container_h_#handler.handler_id").save();
 					}, 
 					run: function() {
 			        	Builder.runHandler("<?=$arr_param['module']['name']?>", "<?=$arr_param['handler']['event']?>");         
 			    	}
 			    }));	      		
       	 };
		initBespin($$("#hcodehcontainer"+"#handler.handler_id .hcodeh"));
      	
//*
		var initHtml = function(list) {
      		var item = list.pop();
      		if (!item || !$(item)) {
      			setTimeout(function() {
         	    	$("container_h_#handler.handler_id").save(true);
      			}, 100);
      			return;
      		}
	        Builder.applyBespin(item, function(fr) {
	            var arr = [];
	          	$A(Builder.tagRoot.childNodes).each(function(item) {
	          		arr.push(item.text);
	          	});
	          	fr.txt.addKeywords("<c"+":", arr);

	            fr.txt.addKeywords(null, [
					"<c"+":if cond=\"\">\n</"+"c:if>", "<c"+":else />", "<c"+":include event=\"\" />", "<c"+":hook name=\"\" />", "<c"+":foreach var=\"\" name=\"\">", "<c"+":print value=\"\" />", "<c"+":input type=\"\" class=\"\" name=\"\" value=\"\" label=\"\" overlabel=\"\" />", "<c"+":body/>", 
					"<a href=\"\"></a>", "<div class=\"clear\"><!-- clear floating --></div>", "<form method=\"post\" action=\"\">\n</form>", "<button type=\"\"></button>"
				]);
	            
				initHtml(list);
		    }, Object.extend(Builder.prailsNamespace, {
				id: "container_h_#handler.handler_id",
				save: function() {
					parent.$("container_h_#handler.handler_id").save();
				}, 
				run: function() {
		        	Builder.runHandler("<?=$arr_param['module']['name']?>", "<?=$arr_param['handler']['event']?>");         
		    	}
		    }));
    	 };
    	 initHtml($$("#hhtmlcodehcontainer"+"#handler.handler_id .hhtmlcodeh"));//*/
      })();

      Ext.getCmp("portlet_content_h_<?=(int)$arr_param['handler']['handler_id']?>").getTopToolbar().add({
				xtype: "button",
				text: "Save",
				iconCls: "save",
				handler: function(e) {
					$("container_h_#handler.handler_id").save();
				}
			}, "-", {
				xtype: "button",
				text: "Run",
				tooltip: "Ctrl+Shift+X",
				iconCls: "run",
				disabled: (<?=(int)$arr_param["handler"]["handler_id"]?> == 0 ? true : false),
				handler: function(e) {
					Builder.runHandler("<?=$arr_param['module']['name']?>", "<?=$arr_param['handler']['event']?>");					
				}
			}, "-", {
				xtype: "button",
				text: "Debug",
				iconCls: "debug",
				tooltip: '<?=ENV_PRODUCTION === true ? "Debugging is only available on development instances" : "Run debugger"?>',
				disabled: (<?=(int)$arr_param["handler"]["handler_id"]?> <= 0 || <?=ENV_PRODUCTION === true ? "true" : "false"?> ? true : false),
				handler: function(e) {
					Builder.debug('#handler.fk_module_id', 'handler', '#handler.handler_id');
				}
			}, "-", {
				xtype: "button",
				text: "Edit URL",
				iconCls: "urls",
				disabled: (<?=(int)$arr_param["handler"]["handler_id"]?> <= 0 || window.Builder.noRewrite ? true : false),
				handler: function(e) {
					Builder.editNiceUrl('#handler.event URL', '#handler.handler_id');
				}
			}, "-", {
				xtype: "button",
				id: "handler.#handler.handler_id_viewHistory.button",
				text: "View History",
				iconCls: "history",
				disabled: (<?=(int)$arr_param["handler"]["handler_id"]?> <= 0 ? true : false),
				handler: function(e) {
					if ($("ha_#handler.handler_id") != null) {
						$("ha_#handler.handler_id").fisheye.dispose();
						$("ha_#handler.handler_id").remove();
						Ext.getCmp("handler.#handler.handler_id_viewHistory.button").setText("View History");
					} else {
						Builder.browseHandlerHistory(#handler.handler_id);
						Ext.getCmp("handler.#handler.handler_id_viewHistory.button").setText("Leave History");
					}
				}
			}, "-", {
				xtype: "button",
				text: "Add Endpoint",
				tooltip: "Inserts an endpoint for submitting forms. In order to reach it, make sure a variable of the endpoint's name is posted.",
				iconCls: "form",
				handler: function(e) {
					// first ask for the endpoint's name
					var name = prompt("Please enter the endpoint's name:");
					name = name.replace(/^\s+|\s+$|[^a-zA-Z0-9]+/gi, '');
					if (!name || name.length <= 0) return;
					
					var found = false;
			        $('container_h_<?=$arr_param['handler']['handler_id']?>').select(".tab-list .hcodeh").each(function(item) {
			        	var t = item.title;
			        	if (t == name) found = true;
			        });
			        if (found) {
			        	Ext.Msg.alert("Problem", "An endpoint with this name already exists.");
			        	return;
			        }
					
					content = $("endpoint_#handler.handler_id").innerHTML.replace(/\[name\]/gi, name);
					window["codeTabs#handler.handler_id"].add({title: name, id: "<?=(int)$arr_param['handler']['handler_id']?>"+name, html: content});

					setTimeout(function() {
						window["codeTabs#handler.handler_id"].setActiveTab("<?=(int)$arr_param['handler']['handler_id']?>"+name);
					}, 100);
					
					var id = 'codeh<?=(int)$arr_param['handler']['handler_id']?>'+name;
					new PeriodicalExecuter(function(pe) {
						var item = $(id);
						if (!item) return;
						pe.stop();
				        Builder.applyBespin(item, function(fr) {
					    	$("container_h_#handler.handler_id").addKeywords = function(txt) {
				        		txt.addKeywords(null, function(txt) {
				        			var res = [];
				        			var matches = txt.value.substr(0, txt.selectionEnd).match(/\$[a-zA-Z_][a-zA-Z_0-9]*\b/gi);
				        			if (matches) {
					        			for (var a = 0; a < matches.length; a++) {
					        				if ((",$arr_param,$data,$SERVER,$SECURE_SERVER,$currentLang,$_GET,$_POST,$_REQUEST,$_COOKIE,$_SERVER,"+res.join(",")+",").indexOf(matches[a]) < 0) {
					        					res.push(matches[a]);
					        				}
					        			}
				        			}
				        			return res;
				        		});
					          	var arr = [];
					          	$A(Builder.root.findChild("id", <?=(int)$_SESSION["module_id"]?>).datas).each(function(item) {
					          		arr.push(item.text);
					          	});
					          	txt.addKeywords("\\$data->", arr);
					          	txt.addKeywords("Generator::", ["getInstance()"]);
					          	txt.addKeywords("Generator::getInstance\\(\\)->", ["getTitle()", "setTitle(\"New Title\")", "getDescription()", "setDescription($description)", "setIsAjax(true)", "setKeywords($keywords)", "addHeader(\"<meta name='robots' content='index, follow' />\")", "getLanguage()"]);
					          	txt.addKeywords("Generator::getInstance\\(\\)->getLanguage\\(\\)->", ["getText($identifier)", "selectTextByIdentifier($itentifier)", "listAllTextsFromRoot($rootIdentifier)", "findTextByContent($searchString)", "getAllTextsByIdentifier($identifier)"]);
					          	txt.addKeywords("\\$currentLang->", ["getText($identifier)", "selectTextByIdentifier($itentifier)", "listAllTextsFromRoot($rootIdentifier)", "findTextByContent($searchString)", "getAllTextsByIdentifier($identifier)"]);
					          	txt.addKeywords(null, ["$_SERVER", "$_COOKIE", "$_REQUEST", "$_GET", "$_POST", "$data", "$arr_param", "$SERVER", "$SECURE_SERVER", "$currentLang", "out($arr_param)", "invoke($event, $arr_param)", "checkFields($arr_toCheck, $arr_keys)", "Generator", "scaleEmbed($embed, $width, $height)", "isEmbed($embed)", "isExternalURL($string)", "if_set($a, $b)", "set_var($a, $b)", "getUserLanguage($arr_allowedLanguages, $defaultLanguage)", "wordCut($text, 200, \"...\")", "removeDir($path, true)", "hyperlink($text)", "timeDiff($time)", "toUTF8($string)", "jumpTo($url)", "createThumbnail($src, $dest, 64, 64)", "getThumbnailFromEmbed($embed)", "sendMail($to, $subject, $content, $fromName, $fromAddress)", "doGet($url)", "doPost($url, $postData)", "array_merge_recursive_distinct($arr1, $arr2)", "one_of($a, $b, ...)", "receiveFile($fileName, $targetPath)"]);
				        	};
				        	$("container_h_#handler.handler_id").addKeywords(fr.txt);
				        	
							item.down("iframe").style.height = (parseInt($("hformh<?=(int)$arr_param['handler']['handler_id']?>").parentNode.parentNode.style.height) - 175) + "px";
					    }, Builder.prailsNamespace);
					}, 0.025);
					
					// if there are tabs for the handler code already, add one
					// else wrap it into tabs and add one
				}
			}, {
				xtype: "button",
				text: "Add Template",
				tooltip: "Inserts a template for including or outputting.",
				iconCls: "form",
				handler: function(e) {
					// first ask for the endpoint's name
					var name = prompt("Please enter the template's name:");
					name = name.replace(/^\s+|\s+$|[^a-zA-Z0-9]+/gi, '');
					if (!name || name.length <= 0) return;
						
					var found = false;
				    $('container_h_<?=$arr_param['handler']['handler_id']?>').select(".tab-list .hhtmlcodeh").each(function(item) {
				       	var t = item.title;
				       	if (t == name) found = true;
				    });
				    if (found) {
				       	Ext.Msg.alert("Problem", "A template with this name already exists for that handler.");
				       	return;
				    }
						
					content = $("template_#handler.handler_id").innerHTML.replace(/\[name\]/gi, name);
					window["htmlCodeTabs#handler.handler_id"].add({title: name, id: "hhtml_<?=(int)$arr_param['handler']['handler_id']?>"+name, html: content});

					setTimeout(function() {
						window["htmlCodeTabs#handler.handler_id"].setActiveTab("hhtml_<?=(int)$arr_param['handler']['handler_id']?>"+name);
					}, 100);
						
					var id = "#hhtml_<?=(int)$arr_param['handler']['handler_id']?>"+name+" .hhtmlcodeh";
					new PeriodicalExecuter(function(pe) {
						var item = $$(id)[0];
						if (!item) return;
						pe.stop();
				        Builder.applyBespin(item, function(fr) {
				            item.down("iframe").style.height = (parseInt($("hformh<?=(int)$arr_param['handler']['handler_id']?>").parentNode.parentNode.style.height) - 150) + "px";
				            
				            var arr = [];
				          	$A(Builder.tagRoot.childNodes).each(function(item) {
				          		arr.push(item.text);
				          	});
				          	fr.txt.addKeywords("<c"+":", arr);

				            fr.txt.addKeywords(null, [
								"<c"+":if cond=\"\">\n</"+"c:if>", "<c"+":else />", "<c"+":include event=\"\" />", "<c"+":hook name=\"\" />", "<c"+":foreach var=\"\" name=\"\">", "<c"+":print value=\"\" />", "<c"+":input type=\"\" class=\"\" name=\"\" value=\"\" label=\"\" overlabel=\"\" />", "<c"+":body/>", 
								"<a href=\"\"></a>", "<div class=\"clear\"><!-- clear floating --></div>", "<form method=\"post\" action=\"\">\n</form>", "<button type=\"\"></button>"
							]);
					    }, Object.extend(Builder.prailsNamespace, {
							id: "container_h_#handler.handler_id",
							save: function() {
								parent.$("container_h_#handler.handler_id").save();
							}, 
							run: function() {
					        	Builder.runHandler("<?=$arr_param['module']['name']?>", "<?=$arr_param['handler']['event']?>");         
					    	}
					    }));
					}, 0.025);
						
					// if there are tabs for the handler code already, add one
					// else wrap it into tabs and add one
				}
			});
			Ext.getCmp("portlet_content_h_<?=(int)$arr_param['handler']['handler_id']?>").getTopToolbar().doLayout();
			window["codeTabs#handler.handler_id"] = new Ext.TabPanel({
			    applyTo: 'hcodehcontainer#handler.handler_id',
			    activeTab: 0,
			    width: "auto",
			    defaults: {
			    	width: "auto",
			    	closable: true,
				    listeners: {
				    	beforeclose: function(p) {
				    		if (p.title != "Default") {
				    			return confirm("Do you really want to remove that endpoint?");
				    		} else {
				    			return false;
				    		}
				    	},
				    	activate: function(p) {
				    		try {
				    			p.el.dom.down("iframe").contentWindow.updateSize();
				    		} catch(e) {};
				    	}
				    }
			    },
			    deferredRender: false,
			    height: (parseInt($("hformh<?=(int)$arr_param['handler']['handler_id']?>").parentNode.parentNode.style.height) - 150),
			    autoTabs: true
			});
			window["htmlCodeTabs#handler.handler_id"] = new Ext.TabPanel({
			    applyTo: 'hhtmlcodehcontainer#handler.handler_id',
			    activeTab: 0,
			    width: "auto",
			    defaults: {
			    	width: "auto",
			    	closable: true,
				    listeners: {
				    	beforeclose: function(p) {
				    		if (p.title != "Default") {
				    			return confirm("Do you really want to remove that template?");
				    		} else {
				    			return false;
				    		}
				    	},
				    	activate: function(p) {
				    		try {
				    			p.el.dom.down("iframe").contentWindow.updateSize();
				    		} catch(e) {};
				    	}
				    }
			    },
			    deferredRender: false,
			    height: (parseInt($("hformh<?=(int)$arr_param['handler']['handler_id']?>").parentNode.parentNode.style.height) - 150),
			    autoTabs: true
			});
			setTimeout(function() {
				$$("#hcodehcontainer#handler.handler_id .x-panel-body, #hcodehcontainer#handler.handler_id .x-panel, #hhtmlcodehcontainer#handler.handler_id .x-panel-body, #hhtmlcodehcontainer#handler.handler_id .x-panel").invoke("setStyle", "width: auto;");
			}, 100);
			Ext.QuickTips.init();			
		}, 10);
	//]]>
	</script>
</form>
</div>